package com.qf.servlet;

import com.qf.entity.User;
import com.qf.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@WebServlet(urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        //接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String birthday = req.getParameter("birthday");
        String[] powers = req.getParameterValues("power");

        //校验

        //封装实体类
        try {
            User user = new User()
                    .setUsername(username)
                    .setPassword(password)
                    .setName(name)
                    .setAge(Integer.parseInt(age))
                    .setBirthday(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse(birthday))
                    .setPowers(Arrays.asList(powers));

            //保存数据
            int result = userService.register(user);
            if (result > 0) {
                //注册成功
                resp.sendRedirect("login.jsp");
                return;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        resp.sendRedirect("register.jsp?status=1");
    }
}
